import re
import os
from datetime import datetime, timedelta

def parse_time(time_str):
    return datetime.strptime(time_str, '%H:%M:%S,%f')

def format_time(time_obj):
    return time_obj.strftime('%H:%M:%S,%f')[:-3]

def merge_srt_files(input_files, output_file):
    time_offset = timedelta()
    try:
        with open(output_file, 'w', encoding='utf-8') as outfile:
            counter = 1
            for file in input_files:
                with open(file, 'r', encoding='utf-8') as infile:
                    content = infile.read().strip().split('\n\n')
                    for block in content:
                        lines = block.split('\n')
                        # 更新序号
                        lines[0] = str(counter)
                        # 解析时间
                        time_line = lines[1]
                        start_time_str, end_time_str = time_line.split(' --> ')
                        start_time = parse_time(start_time_str)
                        end_time = parse_time(end_time_str)
                        # 调整时间
                        new_start_time = start_time + time_offset
                        new_end_time = end_time + time_offset
                        # 更新时间行
                        lines[1] = f"{format_time(new_start_time)} --> {format_time(new_end_time)}"
                        new_block = '\n'.join(lines)
                        outfile.write(new_block + '\n\n')
                        counter += 1
                    # 更新时间偏移为当前文件最后一个字幕的结束时间相对于 0 时刻的偏移
                    last_end_time = parse_time(end_time_str)
                    zero_time = parse_time('00:00:00,000')
                    time_offset += (last_end_time - zero_time)
        return True, f"合并后的 SRT 文件已成功保存为 {output_file}"
    except FileNotFoundError as e:
        return False, f"错误: 文件 {e.filename} 未找到。"
    except Exception as e:
        return False, f"错误: 处理文件时发生未知错误: {e}"


def get_srt_files(folder_path):
    return [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.srt')]